package com.back.network.netty.handlers;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.back.network.netty.protocol.IdleCheckHandler;
import com.back.network.netty.protocol.ProxyMessageDecoder;
import com.back.network.netty.protocol.ProxyMessageEncoder;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

@Component
public class ChildProxyChannel extends ChannelInitializer<SocketChannel> {
	@Autowired
	private ObjectFactory<ServerChannelHandler> serverChannelHandler;

	/**
	 * max packet is 2M.
	 */
	private static final int MAX_FRAME_LENGTH = 2 * 1024 * 1024;

	private static final int LENGTH_FIELD_OFFSET = 0;

	private static final int LENGTH_FIELD_LENGTH = 4;

	private static final int INITIAL_BYTES_TO_STRIP = 0;

	private static final int LENGTH_ADJUSTMENT = 0;

	@Override
	public void initChannel(SocketChannel ch) throws Exception {
		try {
			ch.pipeline().addLast(new ProxyMessageDecoder(MAX_FRAME_LENGTH, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH,LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP));
			ch.pipeline().addLast(new ProxyMessageEncoder());
			ch.pipeline().addLast(new IdleCheckHandler(IdleCheckHandler.READ_IDLE_TIME, IdleCheckHandler.WRITE_IDLE_TIME, 0));
			ch.pipeline().addLast(serverChannelHandler.getObject());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
